#include "mat_leveldata.h"
#include "mat_ui_popupanimator.h"
#include "mat_gamerule.h"
#include "gen_game_state.h"
#include "mat_animation_mgr.h"

#include "num/rand.h"
#include "script/scripthelper.h"

#include "util/mmgr.h"		    // Needs to come in early
#include "util/common_macros.h"		// macros
#include "util/log.h"		    // logging
#include <cassert>

using namespace script;

MATLevelDataSet&	MATLevelDataSet::Instance()
{
	static	MATLevelDataSet	Inst;
	return Inst;
}

MATLevelDataSet::MATLevelDataSet()
{
	Reload();
}


void	MATLevelDataSet::Reload()
{
	Load("infos/levels.lua");
	if (!GetState()) return;
	LuaPlus::LuaObject	Table = GetTable("Levels");
	if (!Table.IsTable()) return;
	m_LevelData.ClearSet();
	char Buffer[256];
	
	for (int i=0; i<Table.GetTableCount(); i++)
	{
		LuaPlus::LuaObject	Obj = Table.GetByIndex(i+1);
		MATLevelData*	pData = new MATLevelData();

		pData->Index = ScriptHelper::GetTableInt(Obj, "Index");
		std::string GameType = ScriptHelper::GetTableString(Obj, "Type");
		pData->m_GameType = MATLevelData::MapNameToGameType(GameType);
		pData->Score[0] = ScriptHelper::GetTableInt(Obj, "Score1");
		pData->Score[1] = ScriptHelper::GetTableInt(Obj, "Score2");
		pData->Score[2] = ScriptHelper::GetTableInt(Obj, "Score3");
		pData->Move = ScriptHelper::GetTableInt(Obj, "Move");
		pData->Time = ScriptHelper::GetTableInt(Obj, "Time" , 30);
		pData->Gem1Count = ScriptHelper::GetTableInt(Obj, "Gem1Count");
		pData->Gem2Count = ScriptHelper::GetTableInt(Obj, "Gem2Count");
		pData->GemTypeCountInGame = ScriptHelper::GetTableInt(Obj, "GemTypeCountInGame");
		pData->m_ToSpawnMoreBomb = ScriptHelper::GetTableBool(Obj, "SpawnBomb");

		sprintf(Buffer, "%i", pData->Index);
		m_LevelData.AddElement(Buffer, pData);
		
	}
}

GAME_TYPE	MATLevelData::MapNameToGameType(const std::string& TypeName)
{
	for (unsigned int i=0; i< GAMETYPE_COUNT; i++)
	{
		if (strcmpi(MapGameTypeToName((GAME_TYPE)i).c_str(), TypeName.c_str())==0) return (GAME_TYPE)i;
	}
	return GAMETYPE_UNKNOWN;
}

std::string		MATLevelData::MapGameTypeToName(GAME_TYPE	Type)
{
	switch (Type)
	{
	
	case GAMETYPE_MULTIPLAYER: return "MULTIPLAYER"; break;

	case GAMETYPE_SCORE_WITHMOVE: return "SCORE_WITHMOVE"; break;
	case GAMETYPE_GETGEMSTOCOUNT_WITHMOVE: return "GETGEMSTOCOUNT_WITHMOVE"; break;
	case GAMETYPE_CLEAR_TILES_WTIHMOVE: return "CLEAR_TILES_WTIHMOVE"; break;

	case GAMETYPE_SCORE_WITHTIMEOUT: return "SCORE_WITHTIMEOUT"; break;	
	case GAMETYPE_GETGEMSTOCOUNT_WITHTIMEOUT: return "GETGEMSTOCOUNT_WITHTIMEOUT"; break;
	case GAMETYPE_CLEAR_TILES_TIMEOUT: return "CLEAR_TILES_TIMEOUT"; break;

	case GAMETYPE_REACH_MOVECOUNT: return "REACH_MOVECOUNT"; break;	

	default:
		break;
	
	}
	return "unknown";
}

